package com.se.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

import javax.servlet.http.HttpServletRequest;

import com.se.data.CapturedRequest;

public class CapturedRequestBuilder {

	private static final String CAPTURE_PREFIX = "/capture";
	
	private static final String FORWARD_SLASH = "/";
	
	public CapturedRequest build(HttpServletRequest request) throws IOException {
		StringWriter stringWriter = new StringWriter();
		PrintWriter printWriter = new PrintWriter(stringWriter);
		RequestPrinter printer = new RequestPrinter(request, printWriter);
		String title = printer.printRequest();
		String tag = inferTagFromTitle(title);
		String content = stringWriter.toString();
		return new CapturedRequest(tag, title, content);
	}

	private String inferTagFromTitle(String title) {
		// all titles should include this
		int startIndex = title.indexOf(CAPTURE_PREFIX);
		if (startIndex < 0) {
			return null;
		}
		// extract the next path token
		int fromIndex = startIndex + CAPTURE_PREFIX.length() + 1;
		if (title.length() <= fromIndex) {
			return null;
		}
		int toIndex = title.indexOf(FORWARD_SLASH, fromIndex);
		if (toIndex < 0) {
			return title.substring(fromIndex);
		}
		return title.substring(fromIndex, toIndex);
	}
}
